package com.yunmang.activity.fache;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.yunmang.R;
import com.yunmang.activity.BaseActivity;
import com.yunmang.adapter.PiciManagerAdapter;
import com.yunmang.app.AppConstant;
import com.yunmang.entity.SendBatchBean;
import com.yunmang.http.HttpUtils;
import com.yunmang.utils.CommonUtils;
import com.yunmang.utils.DateUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;
import rx.Subscriber;

/**
 * Created by Administrator on 2017/5/26.
 */
public class TransportManager extends BaseActivity implements AdapterView.OnItemClickListener {
    @InjectView(R.id.toolbar)
    Toolbar mToolbar;
    @InjectView(R.id.et_search)
    EditText etSearch;
    @InjectView(R.id.iv_scan)
    ImageView ivScan;

    @InjectView(R.id.btn_search)
    Button btnSearch;

    @InjectView(R.id.tv_check)
    TextView tvCheck;
    @InjectView(R.id.et_hdbh_search)
    EditText etHdbhSearch;
    @InjectView(R.id.image_scan)
    ImageView imageScan;
    @InjectView(R.id.ll_search)
    LinearLayout llSearch;
    @InjectView(R.id.search)
    Button search;
    @InjectView(R.id.ll_container)
    LinearLayout llContainer;
    @InjectView(R.id.tab_FindFragment_title)
    TabLayout tabLayout;
    @InjectView(R.id.iv_date)
    ImageView ivDate;
    @InjectView(R.id.tv_date)
    TextView tvDate;
    @InjectView(R.id.ll_show)
    LinearLayout llShow;
    @InjectView(R.id.start_date)
    TextView sDate;
    @InjectView(R.id.ll_start)
    LinearLayout llStart;
    @InjectView(R.id.tv_end_date)
    TextView tvEndDate;
    @InjectView(R.id.ll_endstart)
    LinearLayout llEndstart;
    @InjectView(R.id.ll_show_date)
    LinearLayout llShowDate;
    @InjectView(R.id.listview)
    ListView listview;
    private String[] exceptionTitles = new String[]{"所有", "未交接", "已交接"};
    private List<String> tabTitleList;
    private String type ="";//类型
    private PiciManagerAdapter adapter;
    private TimePickerView pvCustomTime, pvendTime;
    private Subscriber<SendBatchBean> subscriber;
    private List<SendBatchBean.ModelBean> dataList;
    @Override
    public int getLayoutId() {
        return R.layout.activity_pici_manager;
    }

    @Override
    public void initView() {
        ButterKnife.inject(this);
        initToolbar();
        initTabLayout();
        initCustomTimePicker();
    }

    private void initToolbar() {
        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setTitle("批次管理");
        mToolbar.setNavigationIcon(R.mipmap.ic_back);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
    }

    private void initTabLayout() {
        tabTitleList = Arrays.asList(exceptionTitles);
        for (int i = 0; i < tabTitleList.size(); i++) {
            tabLayout.addTab(tabLayout.newTab().setText(tabTitleList.get(i)), i);
        }
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        type ="";
                        break;
                    case 1:
                        type ="0";
                        break;
                    case 2:
                        type="1";
                        break;
                    default:
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });
    }

    @Override
    public void initData() {
        dataList=new ArrayList<>();
        sDate.setText(DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD));
        tvEndDate.setText(DateUtil.date2string(new Date(), DateUtil.YYYY_MM_DD));
        adapter=new PiciManagerAdapter(context,dataList);
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(this);
    }

    private void initCustomTimePicker() {
        Calendar selectedDate = Calendar.getInstance();//系统当前时间
        final Calendar startDate = Calendar.getInstance();
        startDate.set(2014, 1, 23);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2027, 2, 28);
        //时间选择器 ，自定义布局
        pvCustomTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                sDate.setText(getTime(date));
                pvCustomTime.dismiss();
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.returnData();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvCustomTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.RED)
                .build();


        //时间选择器 ，自定义布局
        pvendTime = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tvEndDate.setText(getTime(date));
                pvendTime.dismiss();
            }
        })
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setLayoutRes(R.layout.pickerview_custom_time, new CustomListener() {

                    @Override
                    public void customLayout(View v) {
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvendTime.returnData();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvendTime.dismiss();
                            }
                        });
                    }
                })
                .setType(new boolean[]{true, true, true, false, false, false})
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setDividerColor(Color.RED)
                .build();

    }

    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        return format.format(date);
    }


    @OnClick({R.id.image_scan,R.id.search,R.id.ll_show, R.id.ll_start, R.id.ll_endstart, R.id.ll_show_date})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.image_scan:
                CommonUtils.onScanBarcode(this);
                break;
            case R.id.search:
                llShowDate.setVisibility(View.GONE);
                String start = CommonUtils.getTextViewValue(sDate);
                String end = CommonUtils.getTextViewValue(tvEndDate);
                String hdbh = CommonUtils.getTextViewValue(etHdbhSearch);
                int result = end.compareTo(start);
                if (result < 0) {
                    showToast("结束日期不能小于开始日期");
                    return;
                }
                dataList.clear();
                requestData(start, end, hdbh, type);
                break;
            case R.id.ll_show:
                tvDate.setTextColor(getResources().getColor(R.color.colorPrimary));
                llShowDate.setVisibility(View.VISIBLE);
                break;
            case R.id.ll_start:
                pvCustomTime.show();
                break;
            case R.id.ll_endstart:
                pvendTime.show();
                break;
            case R.id.ll_show_date:
                break;
        }
    }

    private void requestData(String start, String end, String hdbh, String type) {
        showWaitingDialog("数据获取中……");
        subscriber=new Subscriber<SendBatchBean>() {
            @Override
            public void onCompleted() {
            }
            @Override
            public void onError(Throwable e) {
                hideWaitingDialog();
                e.printStackTrace();
                adapter.refresh(dataList);
                showToast("获取异常");
            }
            @Override
            public void onNext(SendBatchBean sendBatchBean) {
                hideWaitingDialog();
                if(sendBatchBean.getCode()==200){
                    if(sendBatchBean.getModel().size()>0){
                        dataList=sendBatchBean.getModel();

                    }else{
                        showToast("暂无数据");
                    }
                }else{
                    showToast("获取失败");
                }
                adapter.refresh(dataList);
            }
        };
        HttpUtils.getInstance().getSendBatch(subscriber,start,end, AppConstant.userid,hdbh,type);
    }

    @Override
    public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
        Intent in=new Intent(this,PiciDetailActivity.class);
        in.putExtra("batchid",dataList.get(i).getId()+"");
        startActivity(in);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (result != null) {
            if (result.getContents() == null) {
                Toast.makeText(this, "扫码取消！", Toast.LENGTH_LONG).show();
            } else {
                etSearch.setText(result.getContents());
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}
